#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QFileDialog>
#include <QDir>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QUrl>
#include "HQTextStream.h"
#include <QMessageBox>
#include <QIcon>
#include <QStyle>
#include <QRandomGenerator>
#include <QMediaMetaData>
#include <QFontDialog>
#include <QListWidget>
#include <QListWidgetItem>
#include <QInputDialog>
#include <QMouseEvent>
#include <QMenu>
#include <QGuiApplication>
#include <QStyleHints>
#include <QAudioFormat>
#include <QSize>
#include "help.h"
#include <QTimer>
#include <QColor>
#include <QBrush>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowIcon(QIcon(":/musicIcon.png"));
    this->setWindowTitle("乐悦播放器v0.91");
    StartDo();

    auto mediaplayer = new QMediaPlayer;
    auto audioplayer = new QAudioOutput;
    mediaplayer->setAudioOutput(audioplayer);
    if(GetFileText(musicFileName) != "")
    {
        line = indexLine[nowIndex];
        length = indexLength[nowIndex];
        mediaplayer->setAudioOutput(audioplayer);
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        mediaplayer->play();mediaplayer->pause();
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        ui->musicName->setText(musicname);
        SetCover();
        setMusicMessage(GetType(GetFileText(musicFileName,line,length)));
    }//初始化

    QMenuBar *bar1 = menuBar();
    this->setMenuBar(bar1);
    QMenu * fileMenu = bar1->addMenu("");
    //bar1->setVisible(false);
    addMusicList = fileMenu->addAction("添加至歌单");
    deleteForMusicList = fileMenu->addAction("从此歌单删除");


    QMenuBar *bar2 = menuBar();
    this->setMenuBar(bar2);
    QMenu * fileMenu2 = bar2->addMenu("");
    //bar2->setVisible(false);
    deleteMusicList = fileMenu2->addAction("删除此歌单");

    ui->listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏滚动条
    ui->musicList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->musicList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏滚动条

    if (QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark) {
        ui->listWidget->setStyleSheet("QListWidget::item:selected{color:white;}"

                                      "QListWidget {"
                                      "outline: 0px;"
                                      "background-color: rgba(0, 0, 0, 0); "
                                      "}"

                                      "QListWidget::item { "
                                      "height: 60px;"
                                      "border-bottom: 1px solid rgba(203, 203, 203, 0);"
                                      "margin: 3px,0px,3px,0px;"
                                      "background-color: rgba(203, 203, 203, 5)"
                                      "}"

                                      "QListWidget::item:hover { "
                                      "background-color: rgba(203, 203, 203, 50); "
                                      "}");


        ui->musicList->setStyleSheet("QListWidget::item:selected{color:white;"
                                      "background-color: rgba(203, 203, 203, 100); "
                                      "}"

                                      "QListWidget::item:selected:hover {color:white;"
                                      "background-color: rgba(203, 203, 203, 100); "
                                      "}"

                                      "QListWidget::item { "
                                      "height: 50px;"
                                      "border-bottom: 1px solid rgba(203, 203, 203, 0);"
                                      "margin: 3px,3px,3px,3px;"
                                      "border-radius:8px;}"

                                      "QListWidget {"
                                      "outline: 0px;"
                                      "background-color: rgba(203, 203, 203, 0); "
                                      "border:null;"
                                      "}"

                                      "QListWidget::item:hover { "
                                      "background-color: rgba(203, 203, 203, 50); "
                                      "}");
    } else {
        ui->listWidget->setStyleSheet("QListWidget::item:selected{color:black;}"

                                      "QListWidget {"
                                      "outline: 0px;"
                                      "background-color: rgba(0, 0, 0, 0); "
                                      "}"

                                      "QListWidget::item { "
                                      "height: 60px;"
                                      "border-bottom: 1px solid rgba(203, 203, 203, 100);"
                                      "margin: 3px,0px,3px,0px;"
                                      "background-color: rgba(203, 203, 203, 5)"
                                      "}"

                                      "QListWidget::item:hover { "
                                      "background-color: rgba(203, 203, 203, 50); "
                                      "}");
        ui->musicList->setStyleSheet("QListWidget::item:selected{color:black;"
                                      "background-color: rgba(203, 203, 203, 100); "
                                      "}"

                                      "QListWidget::item:selected:hover {color:black;"
                                      "background-color: rgba(203, 203, 203, 100); "
                                      "}"

                                      "QListWidget::item { "
                                      "height: 50px;"
                                      "border-bottom: 1px solid rgba(203, 203, 203, 0);"
                                      "margin: 3px,3px,3px,3px;"
                                      "border-radius:8px;}"

                                      "QListWidget {"
                                      "outline: 0px;"
                                      "background-color: rgba(203, 203, 203, 0); "
                                      "border:null;"
                                      "}"

                                      "QListWidget::item:hover { "
                                      "background-color: rgba(203, 203, 203, 50); "
                                      "}");
    }//根据黑暗模式设置样式


    connect(ui->about,&QAction::triggered,this,[=]{
        QMessageBox::about(this,"关于","====乐悦播放器====\n\n"
                                      "====版本号:0.91====\n\n"
                                      "====作者:HKL====");
    });
    connect(ui->newupdate,&QAction::triggered,this,[=]{
        QMessageBox::about(this,"更新日志","====v0.91更新日志====\n\n"
                                      "====1.修复了已知bug====\n\n"
                                      "====2.新增定时关闭功能====\n\n"
                                      "====3.优化了UI====\n\n"
                                      "====4.====");
    });
    connect(ui->help,&QAction::triggered,this,[=]{
        help *a = new help;
        a->show();
    });//使用教程
    connect(ui->findme,&QAction::triggered,this,[=]{
        QMessageBox::about(this,"联系","\n邮箱:\n\nhkl2985039856@outlook.com");
    });//联系我

    connect(mediaplayer,&QMediaPlayer::durationChanged,this,[=](qint64 duration){
        ui->time->setRange(0,duration);//设置进度条大小
        QString a0 = "",a1 = "";
        if((duration/1000)/60 < 10){a0 = "0";}
        if((duration/1000)%60 < 10){a1 = "0";}
        ui->EndTime->setText(a0 + QString::number((duration/1000)/60) + ":" + a1 + (QString::number((duration/1000)%60)));//转时间格式
    });
    connect(mediaplayer,&QMediaPlayer::positionChanged,this,[=](qint64 pos){
        ui->time->setValue(pos);//设置进度条
        QString a0 = "",a1 = "";
        if((pos/1000)/60 < 10){a0 = "0";}
        if((pos/1000)%60 < 10){a1 = "0";}
        ui->NowTime->setText(a0 + QString::number((pos/1000)/60) + ":" + a1  + (QString::number((pos/1000)%60)));//转时间格式
        SetLyric(pos);
    });

    connect(ui->FF,&QPushButton::clicked,this,[=]{
        float now = ui->time->value() + 3000;
        mediaplayer->setPosition(now);
    });//快进
    connect(ui->RW,&QPushButton::clicked,this,[=]{
        float now = ui->time->value() - 3000;
        mediaplayer->setPosition(now);
    });//退回

    connect(ui->time,&QSlider::sliderMoved,mediaplayer,&QMediaPlayer::setPosition);

    connect(ui->start,&QPushButton::clicked,this,[=]{
        switch (mediaplayer->playbackState())
        {
        case QMediaPlayer::PlaybackState::StoppedState://停止状态
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            mediaplayer->play();
            break;
        case QMediaPlayer::PlaybackState::PlayingState://播放状态
            mediaplayer->pause();
            break;
        case QMediaPlayer::PlaybackState::PausedState://暂停状态
            mediaplayer->play();
            break;
        }
    });//开始播放
    connect(ui->bigstart,&QPushButton::clicked,this,[=]{
        switch (mediaplayer->playbackState())
        {
        case QMediaPlayer::PlaybackState::StoppedState://停止状态
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            mediaplayer->play();
            break;
        case QMediaPlayer::PlaybackState::PlayingState://播放状态
            mediaplayer->pause();
            break;
        case QMediaPlayer::PlaybackState::PausedState://暂停状态
            mediaplayer->play();
            break;
        }
    });//开始播放

    connect(mediaplayer,&QMediaPlayer::playbackStateChanged,this,[=]{
        switch (mediaplayer->playbackState())
        {
        case QMediaPlayer::PlaybackState::StoppedState://停止状态
            ui->start->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));
            ui->bigstart->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));
            break;
        case QMediaPlayer::PlaybackState::PlayingState://播放状态
            ui->start->setIcon(QIcon(isDark(":/暂停w.png",":/暂停.png")));
            ui->bigstart->setIcon(QIcon(isDark(":/暂停w.png",":/暂停.png")));
            break;
        case QMediaPlayer::PlaybackState::PausedState://暂停状态
            ui->start->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));
            ui->bigstart->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));
            break;
        }
    });//切换播放图标

    connect(mediaplayer,&QMediaPlayer::mediaStatusChanged,this,[=]{
        if(mediaplayer->mediaStatus() == QMediaPlayer::EndOfMedia)
        {
            if(returnPlay == 0)
            {
                movie(1);
            }
            if(returnPlay == 1)
            {
                mediaplayer->play();
                return;
            }
            if(returnPlay == 2)
            {
                // 设置随机数种子
                lastIndex.append(nowIndex);
                nowIndex = QRandomGenerator::global()->bounded(indexLength.size());
                line = indexLine[nowIndex];
                length = indexLength[nowIndex];
            }
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            QString musicname = GetFileText(musicFileName,line,length);
            musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
            mediaplayer->play();ui->musicName->setText(musicname);
            setMusicMessage(GetFileText(musicFileName,line,length));
            SetCover();
        }
    });//下个播放内容设置

    connect(ui->returnPlay1,&QPushButton::clicked,this,[=]{
        if(returnPlay < 2)
        {
            returnPlay++;
        }else{
            returnPlay = 0;
        }
        switch (returnPlay) {
        case 0:ui->returnPlay1->setIcon(QIcon(isDark(":/列表循环w.png",":/列表循环.png")));
            break;
        case 1:ui->returnPlay1->setIcon(QIcon(isDark(":/单曲循环w.png",":/单曲循环.png")));
            break;
        case 2:ui->returnPlay1->setIcon(QIcon(isDark(":/随机播放w.png",":/随机播放.png")));
            break;
        }
    });//切换播放模式 随机 连续 单曲循环

    connect(ui->last,&QPushButton::clicked,this,[=]{
        if(returnPlay == 2)
        {
            if(lastIndex.size() < 1)
            {
                mediaplayer->stop();
                mediaplayer->play();
                return;
            }
            nowIndex = lastIndex[lastIndex.size()-1];
            lastIndex.removeLast();
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            QString musicname = GetFileText(musicFileName,line,length);
            musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
            mediaplayer->play();ui->musicName->setText(musicname);
            setMusicMessage(GetFileText(musicFileName,line,length));
            SetCover();
            return;
        }
        movie(-1);
        mediaplayer->stop();
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        mediaplayer->play();ui->musicName->setText(musicname);
        setMusicMessage(GetFileText(musicFileName,line,length));
        SetCover();
    });//上一个
    connect(ui->biglast,&QPushButton::clicked,this,[=]{
        if(returnPlay == 2)
        {
            if(lastIndex.size() < 1)
            {
                mediaplayer->stop();
                mediaplayer->play();
                return;
            }
            nowIndex = lastIndex[lastIndex.size()-1];
            lastIndex.removeLast();
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            QString musicname = GetFileText(musicFileName,line,length);
            musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
            mediaplayer->play();ui->musicName->setText(musicname);
            setMusicMessage(GetFileText(musicFileName,line,length));
            SetCover();
            return;
        }
        movie(-1);
        mediaplayer->stop();
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        mediaplayer->play();ui->musicName->setText(musicname);
        setMusicMessage(GetFileText(musicFileName,line,length));
        SetCover();
    });//上一个
    connect(ui->next,&QPushButton::clicked,this,[=]{
        if(returnPlay == 2)
        {
            lastIndex.append(nowIndex);
            nowIndex = QRandomGenerator::global()->bounded(indexLength.size());
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            QString musicname = GetFileText(musicFileName,line,length);
            musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
            mediaplayer->play();ui->musicName->setText(musicname);
            setMusicMessage(GetFileText(musicFileName,line,length));
            SetCover();
            return;
        }
        movie(1);
        mediaplayer->stop();
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        mediaplayer->play();ui->musicName->setText(musicname);
        setMusicMessage(GetFileText(musicFileName,line,length));
        SetCover();
    });//下一个
    connect(ui->bignext,&QPushButton::clicked,this,[=]{
        if(returnPlay == 2)
        {
            lastIndex.append(nowIndex);
            nowIndex = QRandomGenerator::global()->bounded(indexLength.size());
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
            mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
            QString musicname = GetFileText(musicFileName,line,length);
            musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
            mediaplayer->play();ui->musicName->setText(musicname);
            setMusicMessage(GetFileText(musicFileName,line,length));
            SetCover();
            return;
        }
        movie(1);
        mediaplayer->stop();
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        mediaplayer->play();ui->musicName->setText(musicname);
        setMusicMessage(GetFileText(musicFileName,line,length));
        SetCover();
    });//下一个

    connect(ui->fileopen,&QAction::triggered,this,[=]{
        QFileDialog open;
        QString rule = open.getExistingDirectory(this,"选择目录","C://");
        rule.replace("//","\\");
        QDir dir(rule);
        QStringList datelist = dir.entryList(QStringList()<<"*.mp3"<<"*.wav"<<"*.flac"<<"*.ogg");
        QString date = datelist.join("|");
        rule.append("/");
        rule.append("|");
        rule.append(date);
        if(date == "")
        {
            QMessageBox::warning(this,"","无可用音乐");
            return;
        }
        for(int i = 1; i <= GetFileTextLine(musicFileName); i++)
        {
            if(rule == GetFileText(musicFileName,i))
            {
                QMessageBox::warning(this,"","已经存在");
                return;
            }
        }
        rule.append("\n");
        WriteFileTextAdd(musicFileName,rule);
        showMusic();
        line = indexLine[nowIndex];
        length = indexLength[nowIndex];
    });//添加音乐文件夹
    connect(ui->openmusic,&QAction::triggered,this,[=]{
        QFileDialog open;
        QStringList rule = open.getOpenFileNames(this,"选择目录","C://",tr("(*.mp3 *.wav *.flac *.ogg)"));
        QString date = rule.join("");
        if(date == "")
        {
            QMessageBox::warning(this,"","无可用音乐");
            return;
        }
        for(int i = 0;i < rule.size();i++)
        {
            if(!Search(musicFileName,rule[i].mid(rule[i].lastIndexOf('/'))).result)
            {
                rule[i].insert(rule[i].lastIndexOf('/')+1,'|');
                rule[i].append("\n");
            }
            WriteFileTextAdd(musicFileName,rule[i]);
        }
        showMusic();
        line = indexLine[nowIndex];
        length = indexLength[nowIndex];
    });//添加音乐文件

    connect(ui->deleteFile,&QAction::triggered,this,[=]{
        InitializeFile(musicFileName);
        InitializeFile("love");
        mediaplayer->stop();
        showMusic();
        ui->musicName->setText("暂无音乐");
        line = 1;length = 2;
    });//清空音乐

    connect(this,&MainWindow::itemClicked,this,[=]{
        mediaplayer->stop();
        mediaplayer->setSource(QUrl::fromLocalFile(GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length)));
        QString musicname = GetFileText(musicFileName,line,length);
        musicname.remove(".mp3");musicname.remove(".wav");musicname.remove(".flac");musicname.remove(".ogg");
        mediaplayer->play();ui->musicName->setText(musicname);
        setMusicMessage(GetFileText(musicFileName,line,length));
        SetCover();
    });//点击选择歌曲


    ui->sound->setRange(0,100);
    ui->sound->setSingleStep(1);


    connect(ui->soundopen,&QPushButton::clicked,this,[=]{
        if(isNoSound == false)
        {
            ui->sound->setValue(0);
            audioplayer->setVolume(0.0);
            isNoSound = true;
            ui->soundopen->setIcon(QIcon(isDark(":/关闭声音w.png",":/关闭声音.png")));
        }else{
            qDebug()<<isNoSound;
            ui->sound->setValue(50);
            audioplayer->setVolume(0.5);
            isNoSound = false;
            ui->soundopen->setIcon(QIcon(isDark(":/中等音量w.png",":/中等音量.png")));
        }
    });//音量
    connect(ui->sound,&QSlider::sliderMoved,this,[=]{
        float sound = ui->sound->value();
        audioplayer->setVolume(sound/100);
        if(ui->sound->value() <= 3)
        {
            isNoSound = true;
            audioplayer->setVolume(0.0);
            ui->soundopen->setIcon(QIcon(isDark(":/关闭声音w.png",":/关闭声音.png")));
        }else{
            isNoSound = false;
            if(ui->sound->value() >= 80)
            {
                ui->soundopen->setIcon(QIcon(isDark(":/最大音量w.png",":/最大音量.png")));
            }else{
                ui->soundopen->setIcon(QIcon(isDark(":/中等音量w.png",":/中等音量.png")));
            }
        }
    });//音量调节


    connect(ui->FontSize,&QAction::triggered,this,[=]{
        bool ok;
        QFont font = QFontDialog::getFont(&ok, this);
        if (ok) {
            ui->listWidget->setFont(font);
            InitializeFile("font");
            WriteFileTextAdd("font",font.toString()+"\n");
            WriteFileTextAdd("font",QString::number(font.pointSize()));
        }
    });//设置字体


    connect(ui->love,&QPushButton::clicked,this,[=]{
        if(Search("love",GetFileText(musicFileName,line,length)).result)
        {
            DeleteFileText("love",(Search("love",GetFileText(musicFileName,line,length))).line);
            ui->love->setIcon(QIcon(isDark(":/收藏w.png",":/收藏.png")));
            showMusic();
            return;
        }
        WriteFileTextAdd("love",GetFileText(musicFileName,line,1) + "|" + GetFileText(musicFileName,line,length) + "\n");
        ui->love->setIcon(QIcon(isDark(":/已收藏w.png",":/已收藏.png")));
    });//添加喜爱

    connect(addMusicList,&QAction::triggered,this,[=]{
        QStringList musiclist;
        if( GetFileTextLine("index") < 1)
        {
            return;
        }
        for(int i = 1;i <= GetFileTextLine("index");i++)
        {
            musiclist << GetFileText("index",i);
        }
        bool ok;
        QString index = QInputDialog::getItem(this,"加入歌单","选择要加入的歌单",musiclist,0,false,&ok);
        if(ok && !Search(index,GetFileText(musicFileName,indexLine[ui->listWidget->currentRow()],indexLength[ui->listWidget->currentRow()])).result)
        {
            WriteFileTextAdd(index,GetFileText(musicFileName,indexLine[ui->listWidget->currentRow()],1) + "|" +
                                        GetFileText(musicFileName,indexLine[ui->listWidget->currentRow()],
                                                indexLength[ui->listWidget->currentRow()]) + "\n");
        }
    });//添加音乐至歌单
    connect(deleteForMusicList,&QAction::triggered,this,[=]{
        if(ui->musicList->currentRow() == 1 ||ui->musicList->currentRow() == 0)
        {

        }else{
            DeleteFileText(GetFileText("index",ui->musicList->currentRow()-2),
                           Search(GetFileText("index",ui->musicList->currentRow()-2),
                                  GetFileText(musicFileName,
                                              indexLine[ui->listWidget->currentRow()],
                                              indexLength[ui->listWidget->currentRow()])).line);

            showMusic();
        }
    });//从歌单删除歌曲

    connect(deleteMusicList,&QAction::triggered,this,[=]{
        if(ui->musicList->currentRow() < 2)
        {return;}
        QFile::remove(GetFileText("index",ui->musicList->currentRow() - 2));
        DeleteFileText("index",ui->musicList->currentRow() - 2);
        ui->musicList->clear();
        ui->musicList->addItem("  所有歌曲");
        ui->musicList->addItem("  喜爱歌曲");
        ui->musicList->addItem("  新建歌单");
        for(int i = 1;i <= GetFileTextLine("index");i++)
        {
            ui->musicList->addItem("  " + GetFileText("index",i));
        }
    });//删除歌单



    connect(ui->big,&QPushButton::clicked,this,[=]{
        if(!isbig)
        {
            ui->allwidget->hide();
            ui->menuBar->hide();
            ui->statusBar->hide();
            ui->bigwidget->show();
            ui->flags->show();
            //ui->dockWidget->minimumSize()
            minsize = this->minimumSize();
            maxsize = this->maximumSize();
            this->setMinimumSize(250,550);
            this->setMaximumSize(250,550);
            this->resize(250,550);
            isbig = true;
            ui->big->setIcon(QIcon(isDark(":/窗口缩小化w.png",":/窗口缩小化.png")));
        }else{
            ui->bigwidget->hide();
            ui->flags->hide();
            this->setMaximumSize(maxsize);
            this->setMinimumSize(minsize);
            this->resize(minsize);
            ui->menuBar->show();
            ui->allwidget->show();
            ui->statusBar->show();
            if(isFlag)
            {
                this->setWindowFlags(Qt::Widget);
                this->show();
                isFlag = false;
            }
            isbig = false;
            ui->big->setIcon(QIcon(isDark(":/窗口放大化w.png",":/窗口放大化.png")));
        }
    });//进入沉浸式界面
    connect(ui->flags,&QPushButton::clicked,this,[=]{
        if(!isFlag)
        {
            this->setWindowFlags(Qt::WindowStaysOnTopHint);
            this->show();isFlag = true;
        }else{
            this->setWindowFlags(Qt::Widget);
            this->show();isFlag = false;
        }
    });//固定窗口于前台
    // 连接SearchMusic按钮的点击事件到一个lambda表达式处理搜索音乐的功能
    connect(ui->SearchMusic,&QPushButton::clicked,this,[=]{
        // 检查搜索框是否为空或仅包含空格，如果是，则不执行搜索
        if(ui->lineEdit->text() == "" || ui->lineEdit->text() == " ")
        {
            return;
        }
        // 删除之前的临时搜索结果文件，以准备新的搜索
        QFile::remove("TemporaryFile(musicSearch)");
        // 执行模糊搜索，查找音乐文件名中包含搜索关键词的项
        Searchreturn date = FuzzySearch(musicFileName,ui->lineEdit->text(),1,2);
        if(date.result)
        {
            // 如果搜索有结果，将结果写入临时文件中
            for(int i = 0;i < date.many;i++)
            {
                WriteFileTextAdd("TemporaryFile(musicSearch)",GetFileText(musicFileName,
                                                                    date.offset[i].line,1)
                                                                    +"|"+
                                                                    GetFileText(musicFileName,
                                                                    date.offset[i].line,
                                                                    date.offset[i].length)+"\n");
            }
            // 更新当前音乐文件名为临时搜索结果文件名
            musicFileName = "TemporaryFile(musicSearch)";
            // 更新UI显示搜索结果
            ui->musiclistName->setText(" 搜索结果");
            ui->musicList->clearSelection();
            showMusic();
            line = 1;length = 2;
        }else{
            // 如果搜索无结果，弹出警告框提示用户
            QMessageBox::warning(this,"搜索","未找到");
        }
    });//搜索音乐

    connect(ui->map1,&QAction::triggered,this,[=]{
        InitializeFile("setMap");
        WriteFileTextAdd("setMap","1");
        SetCover();
    });//设置封面1
    connect(ui->map2,&QAction::triggered,this,[=]{
        InitializeFile("setMap");
        WriteFileTextAdd("setMap","2");
        SetCover();
    });//设置封面2
    connect(ui->map3,&QAction::triggered,this,[=]{
        InitializeFile("setMap");
        WriteFileTextAdd("setMap","3");
        SetCover();
    });//设置封面3
    connect(ui->actionsetMin,&QAction::triggered,this,[=]{
        // 
    });//自定义封面
    
    connect(ui->show,&QAction::triggered,this,[=]{
        InitializeFile("Lyricsetting");
        WriteFileTextAdd("Lyricsetting","1");
        ui->lyrics->show();
    });//歌词显示
    connect(ui->hide,&QAction::triggered,this,[=]{
        InitializeFile("Lyricsetting");
        WriteFileTextAdd("Lyricsetting","0");
        ui->lyrics->hide();
    });//歌词关闭
    QTimer *setTimeToStop = new QTimer();
    connect(ui->action5min,&QAction::triggered,this,[=]{
        setTimeToStop->setInterval(300000);
        setTimeToStop->start();
    });//定时关闭:5min
    connect(ui->action10min,&QAction::triggered,this,[=]{
        setTimeToStop->setInterval(600000);
        setTimeToStop->start();
    });//定时关闭:10min
    connect(ui->action15min,&QAction::triggered,this,[=]{
        setTimeToStop->setInterval(900000);
        setTimeToStop->start();
    });//定时关闭:15min
    connect(ui->action30min,&QAction::triggered,this,[=]{
        setTimeToStop->setInterval(1800000);
        setTimeToStop->start();
    });//定时关闭:30min
    connect(ui->actionsetMin,&QAction::triggered,this,[=]{

        bool ok;
        QString min = QInputDialog::getText(this,"定时播放","请输入定时播放时间",QLineEdit::Normal,QString(),&ok);
        if(ok && !min.isEmpty())
        {
           if(min.toInt() < 0||min.toInt() > 999)
            {
                QMessageBox::warning(this,"","时间过大");
            }else{
                setTimeToStop->setInterval(min.toInt() * 60000);
                setTimeToStop->start();
            }
        }
    });//自定义定时关闭
    connect(setTimeToStop,&QTimer::timeout,this,[=]{
        mediaplayer->pause();
        setTimeToStop->stop();
    });//定时关闭
}


void MainWindow::movie(int movieNum)
{
    if(movieNum < 0)
    {
        if(nowIndex + movieNum >= 0)
        {
            nowIndex += movieNum;
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
        }else{
            nowIndex = indexLine.size() - 1;
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
        }
    }else{
        if(nowIndex + movieNum <= indexLine.size() - 1)
        {
            nowIndex += movieNum;
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
        }else{
            nowIndex = 0;
            line = indexLine[nowIndex];
            length = indexLength[nowIndex];
        }
    }
}//歌曲播放移动

void MainWindow::showMusic()//显示音乐
{
    ui->listWidget->clear();
    QFont font(GetFileText("font",1));
    font.setPointSize(GetFileText("font",2).toInt());
    ui->listWidget->setFont(font);
    indexLine.clear();
    indexLength.clear();
    int how = 1;
    for(int i = 1; i <= GetFileTextLine(musicFileName); i++)
    {
        for(int s = 2; s <= GetFileTextlength(musicFileName,i); s++)
        {
            indexLine.append(i);
            indexLength.append(s);
            //QMediaPlayer getTime;
            QString show = GetFileText(musicFileName,i,s);
            show.remove(".mp3");show.remove(".wav");show.remove(".flac");show.remove(".ogg");
            ui->listWidget->addItem("   [ " + QString::number(how++) + " ]     " + show);
        }
    }
}

void MainWindow::SetCover()//设置歌曲封面
{

    ui->love->setIcon(QIcon(isDark(":/收藏w.png",":/收藏.png")));
    if(Search("love",GetFileText(musicFileName,line,length),2).result)
    {
        ui->love->setIcon(QIcon(isDark(":/已收藏w.png",":/已收藏.png")));
    }
    //设置收藏

    QString url = GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length);
    //"*.mp3"<<"*.wav"<<"*.flac"<<"*.ogg"
    url.remove(".mp3");url.remove(".wav");url.remove(".flac");url.remove(".ogg");
    url.append(".jpg");
    if(!QFile::exists(url))
    {
        //ui->Cover->setText("此歌曲无封面");
        QString smap;
        map = GetFileText("setMap").toInt();
        switch(map)
        {
        case 1:smap = ":/NoMap.png";
            break;
        case 2:smap = ":/map2.jpg";
            break;
        case 3:smap = ":/map3.jpg";
            break;
        case 4:smap = ":/map3.jpg";
            break;
        default:smap = ":/NoMap.png";
            break;
        }
        QPixmap cover(smap);
        cover = cover.scaled(240,240, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->Cover->setPixmap(cover);
        return;
    }
    QPixmap cover(url);
    cover = cover.scaled(240,240, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->Cover->setPixmap(cover);
}
void MainWindow::SetLyric(qint64 nowtime)//设置歌词
{
    QString url = GetFileText(musicFileName,line,1) + GetFileText(musicFileName,line,length);
    //"*.mp3"<<"*.wav"<<"*.flac"<<"*.ogg"
    url.remove(".mp3");url.remove(".wav");url.remove(".flac");url.remove(".ogg");
    url.append(".lrc");
    ui->Lyric->clear();
    if(!QFile::exists(url))
    {
        ui->Lyric->addItem("此歌曲无歌词");
        ui->lyrics->setText("");
        return;
    }
    for(int i = 1;i <= GetFileTextLine(url);i++)
    {
        ui->Lyric->addItem(GetFileText(url,i).mid(10));
        ui->Lyric->addItem("");
        if(GetFileText("Lyricsetting") == "1")
        {
            int min = GetFileText(url,i).mid(1,2).toInt();
            int second = GetFileText(url,i).mid(4,2).toInt();
            int millisecond = GetFileText(url,i).mid(7,2).toInt();
            qint64 lyricTime = min*60000 + second*1000 + millisecond;
            if(nowtime >= lyricTime)
            {
                ui->lyrics->setText(GetFileText(url,i).mid(10));
                if(GetFileText(url,i).mid(0,9) == GetFileText(url,i+1).mid(0,9))
                {
                    ui->lyrics->setText(GetFileText(url,i).mid(10) + "             "+ GetFileText(url,i+1).mid(10));
                }
            }
        }
        if(GetFileText(url,i).mid(0,10) == GetFileText(url,i+1).mid(0,10))
        {
            ui->Lyric->addItem(GetFileText(url,i+1).mid(10));
            i++;
        }
    }
}

void MainWindow::StartDo()//初始化
{
    showMusic();
    ui->tabWidget->setTabText(0, "歌曲信息");
    ui->tabWidget->setTabText(1, "歌词");

    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);// 设置列表控件的上下文菜单策略为自定义
    ui->musicList->setContextMenuPolicy(Qt::CustomContextMenu);// 设置列表控件的上下文菜单策略为自定义
    this->setContextMenuPolicy(Qt::NoContextMenu);// 隐藏菜单栏上的右击菜单

    ui->musicList->addItem("  所有歌曲");
    ui->musicList->addItem("  喜爱歌曲");
    ui->musicList->addItem("  新建歌单");
    ui->musicList->setCurrentRow(0);
    for(int i = 1;i <= GetFileTextLine("index");i++)
    {
        ui->musicList->addItem("  " + GetFileText("index",i));
    }

    ui->returnPlay1->setIcon(QIcon(isDark(":/列表循环w.png",":/列表循环.png")));

    ui->soundopen->setIcon(QIcon(isDark(":/中等音量w.png",":/中等音量.png")));

    ui->big->setIcon(QIcon(isDark(":/窗口放大化w.png",":/窗口放大化.png")));

    ui->start->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));
    ui->bigstart->setIcon(QIcon(isDark(":/播放w.png",":/播放.png")));

    ui->bigwidget->hide();
    ui->flags->hide();
    ui->musiclistName->setText(" 所有音乐");

    if(GetFileText("Lyricsetting") == "1")
    {
        ui->lyrics->show();
    }else{
        ui->lyrics->hide();
    }

}



QString MainWindow::isDark(QString white,QString black){

    if (QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark)
    {
        return white;
    }else{
        return black;
    }
}

QString MainWindow::GetType(QString file)//获取音乐文件类型
{
    if(file.endsWith(".mp3"))
    {
        return "MP3";
    }
    if(file.endsWith(".flac"))
    {
        return "FLAC";
    }
    if(file.endsWith(".ogg"))
    {
        return "OGG";
    }
    if(file.endsWith(".wav"))
    {
        return "WAV";
    }
    return file;
}

void MainWindow::setMusicMessage(QString file)//显示歌曲信息
{
    ui->musictype->setText(GetType(file));
}


void MainWindow::lastPlay()
{

}
void MainWindow::nextPlay()
{

}//这两个函数暂时无用,可删除


MainWindow::~MainWindow()
{
    QFile::remove("TemporaryFile(musicSearch)");
    delete ui;
}

void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    nowIndex = ui->listWidget->row(item);
    line = indexLine[nowIndex];
    length = indexLength[nowIndex];
    emit itemClicked();
}

void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    QMenu *ptr = new QMenu(this);  // 创建一个新的菜单

    // 添加Actions创建菜单项
    ptr->addAction(addMusicList);
    // 添加一个分割线
    ptr->addSeparator();  // 在菜单中添加一个分隔线
    ptr->addAction(deleteForMusicList);

    // 在鼠标光标位置显示右键快捷菜单
    ptr->exec(QCursor::pos());  // 显示菜单
    delete ptr;
}
void MainWindow::on_musicList_customContextMenuRequested(const QPoint &pos)
{
    QMenu *ptr = new QMenu(this);  // 创建一个新的菜单
    // 添加Actions创建菜单项
    ptr->addAction(deleteMusicList);  //
    // 在鼠标光标位置显示右键快捷菜单
    ptr->exec(QCursor::pos());  // 显示菜单
    delete ptr;
}


void MainWindow::on_musicList_itemClicked(QListWidgetItem *item)
{
    if(ui->musicList->row(item) == 0)
    {
        musicFileName = "music";
        ui->musiclistName->setText(" 所有音乐");
    }else{
        if(ui->musicList->row(item) == 1)
        {
            musicFileName = "love";
            ui->musiclistName->setText(" 喜爱音乐");
        }else{
            if(ui->musicList->row(item) == 2)
            {
                bool ok;
                QString listname = QInputDialog::getText(this,"新建歌单","请输入歌单名",QLineEdit::Normal,QString(),&ok);
                if(ok && !listname.isEmpty())
                {
                    if(Search("index",listname).result || (listname == "music" || (listname == "index" || listname == "love")))
                    {
                        QMessageBox::warning(this,"","");
                    }else{
                        WriteFileTextAdd("index",listname + "\n");
                        ui->musicList->addItem("  " + listname);
                    }
                }
                return;
            }else{
                musicFileName = GetFileText("index",ui->musicList->row(item)-2);
                ui->musiclistName->setText(" " + GetFileText("index",ui->musicList->row(item)-2));
            }
        }
    }
    showMusic();
    line = 1;length = 2;
}
